//
//  LauNetworkManager.swift
//  SwiftProject
//
//  Created by Lausen on 2017/7/24.
//  Copyright © 2017年 id. All rights reserved.
//

import UIKit
import AFNetworking

enum LauHttpMethod {
    case GET;
    case POST
}

class LauNetworkManager: AFHTTPSessionManager {

    //1:先声明一个单利
    static let shared = { () -> LauNetworkManager in
        
        //1:实例化一个对象
        let instance = LauNetworkManager()
        
        //2:设置单利的属性
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        //3:返回单例对象
        return instance
    }()
    
    //2:懒加载一个账户对象
    lazy var account = LauAccount()
    
    //3:用户是否登录的计算性属性
    var userLogon: Bool{
        
        return account.access_token != nil
    }
    
    //MARK: -- 专门用来处理token的网络请求
    func tokenRequest(method: LauHttpMethod = .GET, URLString: String,parameters: [String: Any]?,completion:@escaping(_ json: Any?,_ isSuccess: Bool) -> ()) {
        
        guard let token = account.access_token else {
            
            //如果token为nil,那么就直接做失败的回调
            //同样,如果token为nil,也要重新做登录
            NotificationCenter.default.post(
                name: NSNotification.Name(rawValue: LauUserShouldLoginNotification),
                object: nil)
            
            completion(nil, false)

            return
        }
        
        //如果没有传递参数,就去自己拼接token的字典参数
        var params = parameters
        if params == nil {
            
            params = [String: Any]()
        }
        
        params!["access_token"] = token
        
        ///在请求token的函数里面在去做真正的网络请求
        request(method: method, URLString: URLString, parameters: params!, completion: completion)
    }
    
    //MARK: -- 网络请求基本方法的封装
    /// 网络请求的基本方法的封装
    ///
    /// - Parameters:
    ///   - method: 方法是POST还是GET
    ///   - URLString: 接口地址
    ///   - parameters: 参数
    ///   - completion: 完成的回调[返回来的数据/是否成功]
    func request(method: LauHttpMethod = .GET, URLString: String,parameters: [String: Any],completion:@escaping(_ json: Any?,_ isSuccess: Bool) -> ()) -> Void {
        
        //由于GET和POST方法的成功回调特别类似,所以封装一个成功的回到,传入方法中,就可以了
        let success = {(_ data:URLSessionDataTask,_ json: Any?) -> () in
            
            completion(json, true)
        }
        
        //由于GET和POST方法的失败回调特别类似,所以封装一个失败的回调,传入到方法中,就可以了
        let failure = {(_ data:URLSessionDataTask?,_ error: Error) -> () in
            
            //为了安全,token是会过期的,所以需要做token过期的处理
            if (data?.response as? HTTPURLResponse)?.statusCode == 403 {
                
                //发送通知,(谁接受到通知,谁做处理)
                NotificationCenter.default.post(
                    name: NSNotification.Name(rawValue: LauUserShouldLoginNotification),
                    object: "bad Token")
                
                print("token 过期了")
            }

            completion(error, false)
        }
        
        
        if method == .GET {
            
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
            
        }else{
            
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
            
        }
    }
}
